<?php

namespace Xin\ChatGPT\Channels\Moonshot;

use GuzzleHttp\ClientInterface;
use Xin\ChatGPT\Channels\Concerns\Transportable;
use Xin\ChatGPT\Contracts\Completion as CompletionContract;
use Xin\ChatGPT\ResponseUtil;
use Xin\Support\Arr;

class Completion implements CompletionContract
{
    use Transportable {
        Transportable::__construct as private initialize;
    }

    /**
     * @var Channel
     */
    protected $channel;

    public function __construct(ClientInterface $transporter, Channel $channel)
    {
        $this->initialize($transporter);
        $this->channel = $channel;
    }

    /**
     * @inerhitDoc
     */
    public function create(array $messages, array $options = []): array
    {
        $response = $this->transporter->post('chat/completions', [
            'json' => [
                'messages' => $messages,
                'model' => Arr::get($options, 'model', $this->channel->getDefaultModel()),
                'temperature' => Arr::get($options, 'temperature', $this->channel->getDefaultTemperature()),
            ],
        ]);

        return ResponseUtil::toArray($response);
    }

    public function estimateTokenCount($messages, $options = [])
    {
        $response = $this->transporter->post('chat/completions', [
            'json' => [
                'messages' => $messages,
                'model' => Arr::get($options, 'model', $this->channel->getDefaultModel()),
                'temperature' => Arr::get($options, 'temperature', $this->channel->getDefaultTemperature()),
            ],
        ]);
        $result = ResponseUtil::toArray($response);

        return $result;
    }
}
